#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
 @Author: Y-aong
 @FileName: logger.py
 @DateTime: 2024/6/2 14:19
 @Version : 3.10
 @Description: 日志配置
"""
import os
import sys
import logging
from time import strftime


appdata_path = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
PATH = os.path.join(appdata_path, 'orderlines_web_logs')

FMT = "%(asctime)s %(levelname)s %(message)s"
DATE_FMT = "%Y-%m-%d %H:%M:%S"


class Logger(object):
    def __init__(self):
        self.logger = logging.getLogger()
        self.formatter = logging.Formatter(fmt=FMT, datefmt=DATE_FMT)
        self.log_filename = os.path.join(PATH, f'{strftime("%Y-%m-%d")}.log')
        if not os.path.exists(os.path.abspath(PATH)):
            os.makedirs(PATH)
        self.logger.addHandler(self.get_file_handler(self.log_filename))
        self.logger.addHandler(self.get_console_handler())
        # 设置日志的默认级别,Set the default log level
        self.logger.setLevel(logging.INFO)

    # 输出到文件handler的函数定义
    def get_file_handler(self, filename):
        file_handler = logging.FileHandler(filename, encoding="utf-8")
        file_handler.setFormatter(self.formatter)
        return file_handler

    # 输出到控制台handler的函数定义,Output a function definition to the console handler
    def get_console_handler(self):
        console_handler = logging.StreamHandler(sys.stdout)
        console_handler.setFormatter(self.formatter)
        return console_handler


logger = Logger().logger
